from django.shortcuts import render
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.decorators import api_view
from users.serializers import UserSerializer
from users.serializers import FollowerSerializer
from users.models import User
from users.models import Follow
import logging

# Create your views here.
@api_view(['POST', 'GET'])
def user(request):
	userId = request.QUERY_PARAMS.get('userId', None)
	data = request.DATA

	if request.method == 'GET':
		if userId is not None:
			try:
				retreivedUser = User.objects.get(userId = userId)
				userSerializer = UserSerializer(retreivedUser)
			except User.DoesNotExist:
				return Response("invalid user id", status.HTTP_400_BAD_REQUEST)

			return Response(userSerializer.data)
		else:
			return Response("user id is empty", status.HTTP_400_BAD_REQUEST)
	elif request.method == 'POST':
		userSerializer = UserSerializer(data=data)
		if userSerializer.is_valid():
			userSerializer.save()
			return Response(userSerializer.data, status.HTTP_200_OK)
		return Response(userSerializer.errors, status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
def follow(request):
	data = request.DATA
	followerSerializer = FollowerSerializer(data=data)
	if followerSerializer.is_valid():
		followerSerializer.save()
		return Response(followerSerializer.data, status.HTTP_200_OK)
	return Response(followerSerializer.errors, status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def followers(request):
	userId = request.QUERY_PARAMS.get('userId', None)
	followedusers = []
	if userId is not None:
		retreivedUser = Follow.objects.filter(followers = userId)
		for retUser in retreivedUser:
   			followedusers.append(retUser.followings)
   		userSerializer = UserSerializer(followedusers, many=True)

		return Response(userSerializer.data)
	else:
		return Response("user id is empty", status.HTTP_400_BAD_REQUEST)
